// 
//  TextQuestion.cpp
//  LoginSecurity
//  
//  Created by Ryan Latta on 2008-12-01.
//  Copyright 2008 Ryan Latta. All rights reserved.
// 


#ifndef TEXTQUESTION_CPP_RXNCSLEX
#define TEXTQUESTION_CPP_RXNCSLEX
#include "Security.h"
#endif /* end of include guard: TEXTQUESTION_CPP_RXNCSLEX */


TextQuestion::TextQuestion () {
  random->newSeed();
  openFile();
}
TextQuestion::~TextQuestion() {
  closeFile();
}

void TextQuestion::generateQuestion() {
  question = "Please write this word correctly: ";
  answer = " ";
  if(isFileOpen()) {
    answer = getFileChunk();
    question += insertSpaces();
  }
  else {
    //If this says Banana, there is a problem.
    //These statements should never be reached.
    answer = "Banana";
    question += insertSpaces();
  }
  
}
void TextQuestion::generateAnswer() {
}

bool TextQuestion::openFile() {
  file.open("/usr/share/dict/words");
  
  if(isFileOpen()) {
    return true;
  }
  /*
    FIXME Put a secondary file here to load.
  */
  //cout << "Error opening file." << endl;
  return false;
}

bool TextQuestion::closeFile() {
  file.close();
  if(file.fail()) {
    return false;
  }
  return true;
}

string TextQuestion::getFileChunk() {
  unsigned long size;
  ios::pos_type randomPlace;
  
  if(isFileOpen()) {
    
    file.seekg (0, ios::end);
    size = file.tellg();
    file.seekg(0, ios::beg);

/*
  This while loop existed to ensure a word of a certain size existed.
*/
    while (answer.length() <= 1) {
      randomPlace = random->getRandom(0, size);
      
      file.seekg(randomPlace);
      file >> answer; //This could be the middle of a word, so we just throw it away.
      file >> skipws >> answer;
    }
  }
  else {
    answer = "Banana";
  }
  return answer;  
}

string TextQuestion::insertSpaces() {
  int randomSpaces = random->getRandom(0, answer.length()) + answer.length()/2;
  int randomPos;
  string messyWord = answer;
  string junk;
  
  for(int i = 0; i < randomSpaces; ++i)
  {
    junk = getRandomJunk();
    //junk = " ";
    randomPos = random->getRandom(0, answer.length()) + 1;
    messyWord.insert(randomPos, junk);
  }
  messyWord += "\n";
  return messyWord;
  
}

/*
  So here, you can change what nonsense is injected into words.  It is pretty straightforward
  Have fun.
*/
const char TextQuestion::getRandomJunk () {
  const char junk[] =  {" 0 1  "};
  int randomJunk = random->getRandom(0, 6);
  
  return junk[randomJunk];
}

bool TextQuestion::isFileOpen() {
  if(file.is_open()) {
    return true;
  }
  return false;
}

